#include "delay.h"




static uint32_t usTicks = 0;

void delay_init(void)
{
    SystemCoreClockUpdate();
    usTicks = SystemCoreClock / 1000000UL;  
}


void delay_ms(uint16_t nms)
{
    delay_us(nms * 1000);
}


#if DELAY_US == 1

void delay_us(uint32_t nus)
{
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;

    ticks = nus * usTicks;          
    told = SysTick->VAL;

    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow < told)
        {
            tcnt += told - tnow;    
        }
        else
        {
            tcnt += told + (SystemCoreClock / 8) - tnow;
        }

        told = tnow;

        if (tcnt >= ticks)
            break;
    }
}

#elif DELAY_US == 2


void delay_us(uint32_t xus)
{
	SysTick->LOAD = 72 * xus;				//设置定时器重装值
	SysTick->VAL = 0x00;					//清空当前计数值
	SysTick->CTRL = 0x00000005;				//设置时钟源为HCLK，启动定时器
	while(!(SysTick->CTRL & 0x00010000));	//等待计数到0
	SysTick->CTRL = 0x00000004;				//关闭定时器
}


#elif DELAY_US == 3


void delay_us(uint32_t udelay)
{
  __IO uint32_t Delay = udelay * 72 / 8;//(SystemCoreClock / 8U / 1000000U)
    //见stm32f1xx_hal_rcc.c -- static void RCC_Delay(uint32_t mdelay)
  do
  {
    __NOP();
  }
  while (Delay --);
}


#endif
